package com.zxy.study.base.recyclerview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.view.View;

import com.zxy.study.utils.DimenUtils;

import androidx.annotation.ColorRes;
import androidx.annotation.DimenRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;


/**
 * @author amaya.zhao
 * @date 2020/6/28
 */
public class BlueRecyclerViewDivider extends RecyclerView.ItemDecoration {

    //画笔: 绘制间隔线
    private Paint mPaint;
    //间隔图
    private Drawable mDivider;

    //纵向间隔
    private int mVerticalDivider = 0;
    //纵向第一个Item距离父布局的间隔
    private int mFirstVerticalDivider = 0;
    //纵向最后一个Item距离父布局的间隔
    private int mLastVerticalDivider = 0;
    //横向间隔
    private int mHorizontalDivider = 0;
    //横向第一个Item距离父布局的间隔
    private int mFirstHorizontalDivider = 0;
    //横向最后一个Item距离父布局的间隔
    private int mLastHorizontalDivider = 0;

    //是否绘制间隔图案或颜色开关控制
    //是否画最外层边框（注意：isDrawH=true 绘制纵向边框、isDrawV=true 绘制横向边框）
    private boolean isDrawBorder;

    //分割线是否横向对齐
    private boolean isDividerAlignH;

    //分割线是否纵向对齐
    private boolean isDividerAlignV;

    //是否画横向间隔
    private boolean isDrawH;

    //是否绘制纵向间隔
    private boolean isDrawV;

    //用于网格或瀑布流布局
    private int spanCount = 1;

    /**
     * @param context 上下文
     * @param hd      横向间隔
     * @param vd      纵向间隔
     */
    public BlueRecyclerViewDivider(Context context, int hd, int vd) {
        this(context, hd, 0, 0, vd, 0, 0);
    }

    /**
     * @param context
     * @param orientation RecyclerView 列表的方向 {@link RecyclerView#HORIZONTAL, RecyclerView#VERTICAL}
     * @param d           如果orientation是横向的，表示横向间隔，反之亦然
     * @param fd          如果orientation是横向的，表示第一个Item距离父布局的横向间隔，反之亦然
     * @param ld          如果orientation是横向的，最后一个Item距离父布局的横向间隔，反之亦然
     */
    public BlueRecyclerViewDivider(Context context, @RecyclerView.Orientation int orientation, int d, int fd, int ld) {
        boolean isV = orientation == RecyclerView.VERTICAL;
        init(context, isV ? 0 : d, isV ? 0 : fd, isV ? 0 : ld, isV ? d : 0, isV ? fd : 0, isV ? ld : 0);
    }

    /**
     * @param context
     * @param hd      横向间隔
     * @param fhd     横向第一个Item距离父布局间隔
     * @param lhd     横向最后一个Item距离父布局间隔
     * @param vd      纵向间隔
     * @param fvd     纵向第一个Item距离父布局间隔
     * @param lvd     纵向最后一个Item距离父布局间隔
     */
    public BlueRecyclerViewDivider(Context context, int hd, int fhd, int lhd, int vd, int fvd, int lvd) {
        init(context, hd, fhd, lhd, vd, fvd, lvd);
    }

    /**
     * @param context 上下文
     * @param hd      横向间隔
     * @param vd      纵向间隔
     * @param fhd     第一个Item距离父布局的横向间隔
     * @param lhd     最后一个Item距离父布局的横向间隔
     * @param fvd     第一个Item距离父布局的纵向间隔
     * @param lvd     最后一个Item距离父布局的纵向
     *                间隔
     */
    private void init(Context context, int hd, int fhd, int lhd, int vd, int fvd, int lvd) {
        this.mHorizontalDivider = DimenUtils.dpToPx(context, hd);
        this.mLastHorizontalDivider = DimenUtils.dpToPx(context, lhd);
        this.mFirstHorizontalDivider = DimenUtils.dpToPx(context, fhd);
        this.mVerticalDivider = DimenUtils.dpToPx(context, vd);
        this.mLastVerticalDivider = DimenUtils.dpToPx(context, lvd);
        this.mFirstVerticalDivider = DimenUtils.dpToPx(context, fvd);
    }

    private BlueRecyclerViewDivider(Builder builder) {
        mPaint = builder.paint;
        mDivider = builder.dividerDrawable;
        mVerticalDivider = builder.verticalDivider;
        mFirstVerticalDivider = builder.firstVerticalDivider;
        mLastVerticalDivider = builder.lastVerticalDivider;
        mHorizontalDivider = builder.horizontalDivider;
        mFirstHorizontalDivider = builder.firstHorizontalDivider;
        mLastHorizontalDivider = builder.lastHorizontalDivider;
        isDrawBorder = builder.isDrawBorder;
        isDividerAlignH = builder.isDividerAlignH;
        isDividerAlignV = builder.isDividerAlignV;
        isDrawH = builder.isDrawH;
        isDrawV = builder.isDrawV;
    }


    @Override
    public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        if (parent.getLayoutManager() instanceof GridLayoutManager) {
            //网格布局
            getGridItemOffset(outRect, view, parent, state);
        } else if (parent.getLayoutManager() instanceof StaggeredGridLayoutManager) {
            //瀑布流布局
            getStaggeredGridItemOffset(outRect, view, parent, state);
        } else {
            //线性布局
            getLinearItemOffset(outRect, view, parent, state);
        }
    }

    /**
     * 线性布局（LinearLayoutManager）ItemOffset计算
     */
    private void getLinearItemOffset(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        spanCount = 1;

        final int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
        if (((LinearLayoutManager) parent.getLayoutManager()).getOrientation() == LinearLayoutManager.VERTICAL) {
            int top = 0;
            int bottom = mVerticalDivider;
            if (position == 0) {
                top = mFirstVerticalDivider;
            }
            if (parent.getAdapter() != null && position == parent.getAdapter().getItemCount() - 1) {
                bottom = mLastVerticalDivider;
            }
            outRect.set(0, top, 0, bottom);
        } else {
            int left = 0;
            int right = mHorizontalDivider;
            if (position == 0) {
                left = mFirstHorizontalDivider;
            }
            if (parent.getAdapter() != null && position == parent.getAdapter().getItemCount() - 1) {
                right = mLastHorizontalDivider;
            }
            outRect.set(left, 0, right, 0);
        }
    }

    /**
     * 网格布局(GridLayoutManager)ItemOffset计算
     * PS: 不可滚动的方向，每一个Item的宽度（高度）是平均的，所以要经过特殊计算才能保持最外层Item与父布局的间距是我们指定的
     */
    private void getGridItemOffset(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int top = 0, left = 0, right = 0, bottom = 0;

        spanCount = getSpanCount(parent);
        final int itemPosition = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
        final int childCount = parent.getAdapter().getItemCount();

        if (((GridLayoutManager) parent.getLayoutManager()).getOrientation() == RecyclerView.VERTICAL) {
            //上到下，行++，左到右，列++， span为行数
            bottom = mVerticalDivider;
            if (isFirstRow(parent, itemPosition, spanCount, childCount)) {
                top = mFirstVerticalDivider;
            }
            if (isLastRow(parent, itemPosition, spanCount, childCount)) {
                bottom = mLastVerticalDivider;
            }

            //计算每一个item宽度的总间隔
            final int eachItemWidthDivider = (mFirstHorizontalDivider + mLastHorizontalDivider + (spanCount - 1) * mHorizontalDivider) / spanCount;
            left = itemPosition % spanCount * (mHorizontalDivider - eachItemWidthDivider) + mFirstHorizontalDivider;
            right = eachItemWidthDivider - left;

        } else {
            //上到下，列++，左到右，行++， span为列数
            right = mHorizontalDivider;
            if (isFirstRow(parent, itemPosition, spanCount, childCount)) {
                left = mFirstHorizontalDivider;
            }
            if (isLastRow(parent, itemPosition, spanCount, childCount)) {
                right = mLastHorizontalDivider;
            }

            //计算每一个Item高度总间隔
            final int eachItemHeightDivider = (mFirstVerticalDivider + mLastVerticalDivider + (spanCount - 1) * mVerticalDivider) / spanCount;
            top = itemPosition % spanCount * (mVerticalDivider - eachItemHeightDivider) + mFirstVerticalDivider;
            bottom = eachItemHeightDivider - top;
        }
        outRect.set(left, top, right, bottom);
    }

    /**
     * 瀑布流布局（StaggeredGridLayoutManager）ItemOffset计算
     *
     * @param outRect
     * @param view
     * @param parent
     * @param state
     */
    private void getStaggeredGridItemOffset(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        int top = 0, left = 0, right = 0, bottom = 0;

        spanCount = getSpanCount(parent);
        //view在Adapter中的位置
        final int itemPosition = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
        final int childCount = parent.getAdapter().getItemCount();
        //view在瀑布流中的位置
        final int spanIndex = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();

        if (((StaggeredGridLayoutManager) parent.getLayoutManager()).getOrientation() == RecyclerView.VERTICAL) {
            //上到下，行++，左到右，列++， span为行数
            bottom = mVerticalDivider;
            if (isFirstRow(parent, itemPosition, spanCount, childCount)) {
                top = mFirstVerticalDivider;
            }
            if (isLastRow(parent, itemPosition, spanCount, childCount)) {
                bottom = mLastVerticalDivider;
            }

            //计算每一个item宽度的总间隔
            final int eachItemWidthDivider = (mFirstHorizontalDivider + mLastHorizontalDivider + (spanCount - 1) * mHorizontalDivider) / spanCount;
            left = spanIndex * (mHorizontalDivider - eachItemWidthDivider) + mFirstHorizontalDivider;
            right = eachItemWidthDivider - left;

        } else {
            //上到下，列++，左到右，行++， span为列数
            right = mHorizontalDivider;
            if (isFirstRow(parent, itemPosition, spanCount, childCount)) {
                left = mFirstHorizontalDivider;
            }
            if (isLastRow(parent, itemPosition, spanCount, childCount)) {
                right = mLastHorizontalDivider;
            }

            //计算每一个Item高度总间隔
            final int eachItemHeightDivider = (mFirstVerticalDivider + mLastVerticalDivider + (spanCount - 1) * mVerticalDivider) / spanCount;
            top = spanIndex * (mVerticalDivider - eachItemHeightDivider) + mFirstVerticalDivider;
            bottom = eachItemHeightDivider - top;
        }
        outRect.set(left, top, right, bottom);
    }


    @Override
    public void onDraw(@NonNull Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
        super.onDraw(c, parent, state);

        if (mDivider == null && mPaint == null) return;

        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager /*|| layoutManager instanceof StaggeredGridLayoutManager*/) {

            int orientation;
            if (layoutManager instanceof GridLayoutManager) {
                orientation = ((GridLayoutManager) layoutManager).getOrientation();
            } else {
                orientation = ((StaggeredGridLayoutManager) layoutManager).getOrientation();
            }
            switch (orientation) {
                case RecyclerView.HORIZONTAL:
                    if (isDrawH) {
                        drawHorizontalGridOrStaggerH(c, parent);
                    }
                    if (isDrawV) {
                        drawHorizontalGridOrStaggerV(c, parent);
                    }
                    break;
                default:
                    if (isDrawH) {
                        drawVerticalGridOrStaggerH(c, parent);
                    }
                    if (isDrawV) {
                        drawVerticalGridOrStaggerV(c, parent);
                    }
                    break;
            }
        } else if (layoutManager instanceof LinearLayoutManager) {
            drawLinearDivider(c, parent, ((LinearLayoutManager) layoutManager).getOrientation());
        }
    }

    /**
     * 判读是否是第一列
     *
     * @param parent
     * @param pos
     * @param spanCount
     * @return
     */
    private boolean isFirstColumn(RecyclerView parent, View view, int pos, int spanCount) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            return pos % spanCount == 0;
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
            return params.getSpanIndex() == 0;
        }
        return true;
    }

    /**
     * 判断是否是最后一列
     *
     * @param parent
     * @param pos
     * @param spanCount
     * @return
     */
    private boolean isLastColumn(RecyclerView parent, View view, int pos, int spanCount) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            return ((pos + 1) % spanCount) == 0;
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
            return params.getSpanIndex() == spanCount - 1;
        }
        return true;
    }

    /**
     * 判读是否是最后一行
     *
     * @param parent
     * @param pos
     * @param spanCount
     * @param childCount
     * @return
     */
    private boolean isLastRow(RecyclerView parent, int pos, int spanCount, int childCount) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager || layoutManager instanceof StaggeredGridLayoutManager) {
            int lines = childCount % spanCount == 0 ? childCount / spanCount : childCount / spanCount + 1;
            return lines == pos / spanCount + 1;
        }
        return false;
    }

    /**
     * 判断是否是第一行
     *
     * @param parent
     * @param pos
     * @param spanCount
     * @param childCount
     * @return
     */
    private boolean isFirstRow(RecyclerView parent, int pos, int spanCount, int childCount) {
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager || layoutManager instanceof StaggeredGridLayoutManager) {
            return pos < spanCount;
        }
        return pos == 0;
    }

    /**
     * 获取列数
     *
     * @param parent
     * @return
     */
    private int getSpanCount(RecyclerView parent) {
        int spanCount = 1;
        RecyclerView.LayoutManager layoutManager = parent.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            spanCount = ((GridLayoutManager) layoutManager).getSpanCount();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            spanCount = ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
        }
        return spanCount;
    }

    private void drawDivider(Canvas canvas, int left, int top, int right, int bottom) {
        if (mDivider != null) {
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(canvas);
        } else if (mPaint != null) {
            canvas.drawRect(left, top, right, bottom, mPaint);
        }
    }

    /**
     * 绘制线性布局的分割线
     *
     * @param canvas
     * @param parent
     * @param orientation
     */
    private void drawLinearDivider(Canvas canvas, RecyclerView parent, int orientation) {
        if (orientation == LinearLayoutManager.VERTICAL) {
            final int left = parent.getPaddingLeft();
            final int right = parent.getMeasuredWidth() - parent.getPaddingRight();
            final int childSize = parent.getChildCount();

            for (int i = 0; i < childSize - 1; i++) {
                final View child = parent.getChildAt(i);
                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
                final int top = child.getBottom() + layoutParams.bottomMargin;
                final int bottom = top + mVerticalDivider;

                drawDivider(canvas, left, top, right, bottom);
            }
        } else {
            final int top = parent.getPaddingTop();
            final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom();
            final int childSize = parent.getChildCount();
            for (int i = 0; i < childSize - 1; i++) {
                final View child = parent.getChildAt(i);
                RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams();
                final int left = child.getRight() + layoutParams.rightMargin;
                final int right = left + mHorizontalDivider;

                drawDivider(canvas, left, top, right, bottom);
            }
        }
    }


    /**
     * 绘制 “竖直” 网格或瀑布流布局的 横向分割线
     *
     * @param canvas
     * @param parent
     */
    private void drawVerticalGridOrStaggerH(Canvas canvas, RecyclerView parent) {
        final int childCount = parent.getLayoutManager().getItemCount();
        final int parentLeft = parent.getLeft() + parent.getPaddingLeft() + (isDividerAlignV ? mFirstHorizontalDivider : 0);
        final int parentRight = parent.getRight() - parent.getPaddingRight() - (isDividerAlignV ? mLastHorizontalDivider : 0);

        if (isDrawBorder && childCount > 0) {
            //绘制顶部边框
            View child0 = parent.getChildAt(0);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child0.getLayoutParams();
            if (isFirstRow(parent, params.getViewAdapterPosition(), getSpanCount(parent), childCount)) {
                int bottom0 = child0.getTop() - params.topMargin;
                int top0 = bottom0 - mFirstVerticalDivider;
                drawDivider(canvas, parentLeft, top0, parentRight, bottom0);
            }
        }

        int left, top, right, bottom;
        int lastTop = 0;
        View child;
        for (int i = 0; i < parent.getChildCount(); i++) {
            child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            top = child.getBottom() + params.bottomMargin;

            if (isLastRow(parent, params.getViewAdapterPosition(), spanCount, childCount)) {
                lastTop = Math.max(lastTop, top);
            } else {
                //中间
                bottom = top + mVerticalDivider;
                left = child.getLeft() - params.leftMargin - (isFirstColumn(parent, child, params.getViewAdapterPosition(), spanCount) ? isDividerAlignV ? 0 : mFirstHorizontalDivider : 0);
                right = child.getRight() + params.rightMargin + (isLastColumn(parent, child, params.getViewAdapterPosition(), spanCount) ? isDividerAlignV ? 0 : mLastHorizontalDivider : mHorizontalDivider);

                drawDivider(canvas, left, top, right, bottom);
            }
        }

        if (isDrawBorder && lastTop > 0) {
            //最后一行的底部分割线
            drawDivider(canvas, parentLeft, lastTop, parentRight, lastTop + mLastVerticalDivider);
        }
    }

    /**
     * 绘制 “竖直” 网格或瀑布流布局的 竖直分割线
     *
     * @param canvas
     * @param parent
     */
    private void drawVerticalGridOrStaggerV(Canvas canvas, RecyclerView parent) {
        final int childCount = parent.getLayoutManager().getItemCount();
        spanCount = getSpanCount(parent);

        int left, top, right, bottom;
        View child;
        boolean isLastColumn;
        for (int i = 0; i < parent.getChildCount(); i++) {

            child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            top = child.getTop() - params.topMargin;
            top -= isFirstRow(parent, params.getViewAdapterPosition(), spanCount, childCount) && !isDividerAlignH ? mFirstVerticalDivider : 0;
            bottom = child.getBottom() + params.bottomMargin;
            bottom += isLastRow(parent, params.getViewAdapterPosition(), spanCount, childCount) ? (isDividerAlignH ? 0 : mLastVerticalDivider) : mVerticalDivider;

            if (isDrawBorder && isFirstColumn(parent, child, params.getViewAdapterPosition(), spanCount)) {
                //最左侧分割线
                right = child.getLeft() - params.leftMargin;
                left = right - mFirstHorizontalDivider;

                drawDivider(canvas, left, top, right, bottom);
            }

            isLastColumn = isLastColumn(parent, child, params.getViewAdapterPosition(), spanCount);
            if (!isLastColumn || isDrawBorder) {
                left = child.getRight() + params.rightMargin;
                right = left + (isLastColumn ? mLastHorizontalDivider : mHorizontalDivider);
                drawDivider(canvas, left, top, right, bottom);
            }
        }
    }

    /**
     * 绘制 “横向” 网格布局或瀑布流布局的 横向间隔线
     *
     * @param canvas
     * @param parent
     */
    private void drawHorizontalGridOrStaggerH(Canvas canvas, RecyclerView parent) {
        final int childCount = parent.getLayoutManager().getItemCount();
        spanCount = getSpanCount(parent);

        int left, top, right, bottom;
        View child;
        boolean isLastColumn;
        for (int i = 0; i < parent.getChildCount(); i++) {

            child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            left = child.getLeft() - params.leftMargin;
            left -= isFirstRow(parent, params.getViewAdapterPosition(), spanCount, childCount) && !isDividerAlignV ? mFirstHorizontalDivider : 0;
            right = child.getRight() + params.rightMargin;
            right += isLastRow(parent, params.getViewAdapterPosition(), spanCount, childCount) ? isDividerAlignV ? 0 : mLastHorizontalDivider : mHorizontalDivider;

            if (isDrawBorder && isFirstColumn(parent, child, params.getViewAdapterPosition(), spanCount)) {
                bottom = child.getTop() - params.topMargin;
                top = bottom - mFirstVerticalDivider;

                drawDivider(canvas, left, top, right, bottom);
            }
            isLastColumn = isLastColumn(parent, child, params.getViewAdapterPosition(), spanCount);
            if (!isLastColumn || isDrawBorder) {
                top = child.getBottom() + params.bottomMargin;
                bottom = top + (isLastColumn ? mLastVerticalDivider : mVerticalDivider);

                drawDivider(canvas, left, top, right, bottom);
            }
        }
    }

    /**
     * 绘制 “横向” 网格布局或瀑布流布局的 垂直间隔线
     *
     * @param canvas
     * @param parent
     */
    private void drawHorizontalGridOrStaggerV(Canvas canvas, RecyclerView parent) {
        final int childCount = parent.getLayoutManager().getItemCount();

        int left, top, right, bottom;
        int lastLeft = 0;
        View child;

        for (int i = 0; i < parent.getChildCount(); i++) {
            child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            top = child.getTop() - params.topMargin;
            top -= isFirstColumn(parent, child, params.getViewAdapterPosition(), spanCount) ? isDividerAlignH ? 0 : mFirstVerticalDivider : mVerticalDivider;
            bottom = child.getBottom() + params.bottomMargin;
            bottom += isLastColumn(parent, child, params.getViewAdapterPosition(), spanCount) ? isDividerAlignH ? 0 : mLastVerticalDivider : mVerticalDivider;

            if (isFirstRow(parent, params.getViewAdapterPosition(), spanCount, childCount) && isDrawBorder) {
                right = child.getLeft() - params.leftMargin;
                left = right - mFirstHorizontalDivider;

                drawDivider(canvas, left, top, right, bottom);
            }

            if (isLastRow(parent, params.getViewAdapterPosition(), spanCount, childCount)) {
                lastLeft = Math.max(lastLeft, child.getRight() + params.rightMargin);
            } else {

                left = child.getRight() + params.rightMargin;
                right = left + mHorizontalDivider;

                drawDivider(canvas, left, top, right, bottom);
            }
        }

        if (isDrawBorder && lastLeft > 0) {
            top = parent.getTop() + parent.getPaddingTop() + (isDividerAlignH ? mFirstVerticalDivider : 0);
            bottom = parent.getBottom() - parent.getPaddingBottom() - (isDividerAlignH ? mLastVerticalDivider : 0);
            drawDivider(canvas, lastLeft, top, lastLeft + mLastHorizontalDivider, bottom);
        }

    }

    public static class Builder {

        private Context context;
        //画笔（分割线颜色）
        private Paint paint;
        //分割线图案
        private Drawable dividerDrawable;

        private int verticalDivider = 0;
        private int firstVerticalDivider = 0;
        private int lastVerticalDivider = 0;
        private int horizontalDivider = 0;
        private int firstHorizontalDivider = 0;
        private int lastHorizontalDivider = 0;

        //是否画最外层边框(横向和纵向)
        private boolean isDrawBorder;

        //分割线是否横向对齐
        private boolean isDividerAlignH;

        //分割线是否纵向对齐
        private boolean isDividerAlignV;

        //是否画横向间隔
        private boolean isDrawH;

        //是否绘制纵向间隔
        private boolean isDrawV;

        public Builder(Context context) {
            this.context = context;
        }

        /**
         * 设置间隔线颜色
         *
         * @param dividerColor 间隔线颜色
         * @return
         */
        public Builder setDividerColor(int dividerColor) {
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(dividerColor);
            paint.setStyle(Paint.Style.FILL);
            return this;
        }

        /**
         * see {@link #setDividerColor(int)}
         */
        public Builder setDividerColorRes(@ColorRes int colorRes) {
            return setDividerColor(context.getResources().getColor(colorRes));
        }

        /**
         * see {@link #setDividerColor(int)}
         *
         * @param colorStr "#000000" or "#FF000000" 形式的颜色字符串
         * @return
         */
        public Builder setDividerColor(String colorStr) {
            try {
                return setDividerColor(Color.parseColor(colorStr));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return this;
        }

        /**
         * 设置间隔图案
         *
         * @param dividerDrawable 间隔图案
         * @return
         */
        public Builder setDividerDrawable(Drawable dividerDrawable) {
            this.dividerDrawable = dividerDrawable;
            return this;
        }

        /**
         * see {@link #setDividerDrawable(Drawable)}
         */
        public Builder setDividerDrawableRes(@DrawableRes int drawableRes) {
            this.dividerDrawable = context.getResources().getDrawable(drawableRes);
            return this;
        }

        /**
         * 设置纵向间隔距离
         *
         * @param verticalDivider 纵向间隔距离
         * @param isDp            是否为dp单位
         * @return
         */
        public Builder setVerticalDivider(int verticalDivider, boolean isDp) {
            this.verticalDivider = isDp ? DimenUtils.dpToPx(context, verticalDivider) : verticalDivider;
            return this;
        }

        /**
         * see {@link #setVerticalDivider(int, boolean)}
         */
        public Builder setVerticalDividerRes(@DimenRes int divider) {
            return setVerticalDivider(context.getResources().getDimensionPixelOffset(divider), false);
        }

        /**
         * 设置第一个Item距离父布局的纵向间隔
         *
         * @param firstVerticalDivider 第一个Item距离父布局的间隔距离
         * @param isDp                 是否为dp单位
         * @return
         */
        public Builder setFirstVerticalDivider(int firstVerticalDivider, boolean isDp) {
            this.firstVerticalDivider = isDp ? DimenUtils.dpToPx(context, firstVerticalDivider) : firstVerticalDivider;
            return this;
        }

        /**
         * see {@link #setFirstVerticalDivider(int, boolean)}
         */
        public Builder setFirstVerticalDividerRes(@DimenRes int divider) {
            return setFirstVerticalDivider(context.getResources().getDimensionPixelOffset(divider), false);
        }

        /**
         * 设置最后一个Item距离父布局的纵向间隔距离
         *
         * @param lastVerticalDivider 最后一个Item距离父布局的间隔距离
         * @param isDp                是否为dp单位
         * @return
         */
        public Builder setLastVerticalDivider(int lastVerticalDivider, boolean isDp) {
            this.lastVerticalDivider = isDp ? DimenUtils.dpToPx(context, lastVerticalDivider) : lastVerticalDivider;
            return this;
        }

        /**
         * see {@link #setLastVerticalDivider(int, boolean)}
         */
        public Builder setLastVerticalDividerRes(@DimenRes int divider) {
            return setLastVerticalDivider(context.getResources().getDimensionPixelOffset(divider), false);
        }

        /**
         * 设置横向间隔距离
         *
         * @param horizontalDivider 横向间隔距离
         * @param isDp              是否为dp单位
         * @return
         */
        public Builder setHorizontalDivider(int horizontalDivider, boolean isDp) {
            this.horizontalDivider = isDp ? DimenUtils.dpToPx(context, horizontalDivider) : horizontalDivider;
            return this;
        }

        /**
         * see {@link #setHorizontalDivider(int, boolean)}
         */
        public Builder setHorizontalDividerRes(@DimenRes int divider) {
            return setHorizontalDivider(context.getResources().getDimensionPixelOffset(divider), false);
        }

        /**
         * 设置第一个Item与父布局的横向间隔距离
         *
         * @param firstHorizontalDivider 第一个Item与父布局的横向间隔
         * @param isDp                   是否是dp单位
         * @return
         */
        public Builder setFirstHorizontalDivider(int firstHorizontalDivider, boolean isDp) {
            this.firstHorizontalDivider = isDp ? DimenUtils.dpToPx(context, firstHorizontalDivider) : firstHorizontalDivider;
            return this;
        }

        /**
         * see {@link #setFirstHorizontalDivider(int, boolean)}
         */
        public Builder setFirstHorizontalDividerRes(@DimenRes int divider) {
            return setFirstHorizontalDivider(context.getResources().getDimensionPixelOffset(divider), false);
        }

        /**
         * 设置最后一个Item与父布局的横向间隔距离
         *
         * @param lastHorizontalDivider 最后一个Item与父布局的横向间隔距离
         * @param isDp                  是否是dp单位
         * @return
         */
        public Builder setLastHorizontalDivider(int lastHorizontalDivider, boolean isDp) {
            this.lastHorizontalDivider = isDp ? DimenUtils.dpToPx(context, lastHorizontalDivider) : lastHorizontalDivider;
            return this;
        }

        /**
         * see {@link #setLastHorizontalDivider(int, boolean)}
         */
        public Builder setLastHorizontalDividerRes(@DimenRes int divider) {
            return setLastHorizontalDivider(context.getResources().getDimensionPixelOffset(divider), false);
        }

        /**
         * @param hd   横向间隔
         * @param fhd  第一个Item距离父布局的横向间隔
         * @param lhd  最后一个Item距离父布局的横向间隔
         * @param vd   纵向间隔
         * @param fvd  第一个Item距离父布局的纵向间隔
         * @param lvd  最后一个Item距离父布局的纵向间隔
         * @param isDp 是否是dp单位
         */
        public Builder setDivider(int hd, int fhd, int lhd, int vd, int fvd, int lvd, boolean isDp) {
            setHorizontalDivider(hd, isDp);
            setFirstHorizontalDivider(fhd, isDp);
            setLastHorizontalDivider(lhd, isDp);
            setVerticalDivider(vd, isDp);
            setFirstVerticalDivider(fvd, isDp);
            setLastVerticalDivider(lvd, isDp);
            return this;
        }

        /**
         * 设置是否绘制边框
         * PS: {@link #setDrawH(boolean)} 为false,则不会绘制横向边框 and {@link #setDrawV(boolean)} 为false，则不会绘制总线边框
         *
         * @param drawBorder
         * @return
         */
        public Builder setDrawBorder(boolean drawBorder) {
            isDrawBorder = drawBorder;
            return this;
        }

        /**
         * 设置是否绘制横向间隔线
         *
         * @param drawH 是否绘制横向间隔线
         * @return
         */
        public Builder setDrawH(boolean drawH) {
            isDrawH = drawH;
            return this;
        }

        /**
         * 设置是否绘制纵向间隔线
         *
         * @param drawV
         * @return
         */
        public Builder setDrawV(boolean drawV) {
            isDrawV = drawV;
            return this;
        }

        /**
         * 设置绘制横向间隔线时，边框部分是否与内容对齐
         *
         * @param dividerAlignH 是否与横向内容对齐
         * @return
         */
        public Builder setDividerAlignH(boolean dividerAlignH) {
            isDividerAlignH = dividerAlignH;
            return this;
        }

        /**
         * 设置绘制纵向间隔线时，边框部是否与内容对齐
         *
         * @param dividerAlignV
         * @return
         */
        public Builder setDividerAlignV(boolean dividerAlignV) {
            isDividerAlignV = dividerAlignV;
            return this;
        }

        public BlueRecyclerViewDivider build() {
            return new BlueRecyclerViewDivider(this);
        }
    }
}
